package com.jzg.mvc.api.cabinet;

import java.util.ArrayList;
import java.util.List;


import com.jfinal.core.Path;
import com.jfinal.kit.StrKit;
import com.jzg.common.controller.BaseController;
import com.jzg.common.model.biz.CabCard;
import com.jzg.common.model.sys.SysDic;
import com.jzg.common.model.sys.SysDicItem;
import com.jzg.common.util.UuidUtil;


@Path(value = "/api/cab/label", viewPath = "")
public class LabelController extends BaseController{
	
	public void listData() {
		List<CabCard> cabCard = CabCard.dao.find("select * from "+CabCard.TABLE_NAME+" where cabId=? order by serial  ",this.get("cabId"));
		renderSuccess("查询成功！", cabCard);
	}
	
	/***
	 * 保存
	 */
	public void save() {
		CabCard cabCard = getModel(CabCard.class);
		if (StrKit.notBlank(cabCard.getId())) {
			CabCard module = CabCard.dao.findFirst("SELECT * FROM " + CabCard.TABLE_NAME + " WHERE CABID=? AND VALUE=? AND ID!=?", cabCard.getCabId(),cabCard.getValue(),cabCard.getId());
			if (module != null) {
				renderError("【"+module.getValue()+"】标签已存在！");
				return;
			}
			SysDicItem item = SysDicItem.dao.findById(cabCard.getItemId());
			if(item!=null) {
				cabCard.setCode(item.getCODE());
			}
			if (cabCard.update()) {
				renderSuccess("更新成功！");
			} else {
				renderError("更新失败！");
			}
		} else {
			CabCard module = CabCard.dao.findFirst("SELECT * FROM " + CabCard.TABLE_NAME + " WHERE CABID=? AND VALUE=? ", cabCard.getCabId(),cabCard.getValue());
			if (module != null) {
				renderError("【"+module.getValue()+"】标签已存在！");
				return;
			}
			cabCard.setId(UuidUtil.getUUID());
			SysDicItem item = SysDicItem.dao.findById(cabCard.getItemId());
			if(item!=null) {
				cabCard.setCode(item.getCODE());
			}
			if (cabCard.save()) {
				renderSuccess("保存成功！");
			} else {
				renderError("保存失败！");
			}
		}

	}
	
	/***
	 * 删除
	 * @throws Exception
	 */
	public void delete() throws Exception {
		String id = getPara("id");
		CabCard cabCard = CabCard.dao.findById(id);
		if (cabCard != null) {
			if (cabCard.delete()) {
				renderSuccess("删除成功！");
			} else {
				renderError("删除失败！");
			}
		} else {
			renderError("数据不存在,请刷新后再试!");
		}
	}
	
	public void getSelectData() {
		
		List<SysDicItem> items = new ArrayList<SysDicItem>();
		SysDic sysDic = SysDic.dao.findFirst("SELECT * FROM "+SysDic.TABLE_NAME+" WHERE CODE='cabinet-label' " );
		if(sysDic!=null) {
			items = SysDicItem.dao.find("SELECT *FROM "+SysDicItem.TABLE_NAME+" WHERE DICID=? ",sysDic.getID());
		}
		
		renderSuccess("查询成功！", items);
	}
	
	
}
